<!-- 用户管理 -->
<template>
  <div class="app-container">
    <!-- 用户列表 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card shadow="never" class="table-container">
          <el-tree
            style="max-width: 600px"
            :data="orgTreeLst"
            :props="defaultProps"
            :default-expand-all="true"
            @node-click="handleOrgQuery"
          />
        </el-card>
      </el-col>
      <el-col :span="18">
        <div v-if="isShowSearchBtn" class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="关键字" prop="title">
              <el-input
                v-model="queryParams.title"
                placeholder="用户名/昵称/手机号"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="状态" prop="is_hid">
              <el-select
                v-model="queryParams.is_hid"
                placeholder="全部"
                clearable
                class="!w-[100px]"
              >
                <el-option label="启用" value="0" />
                <el-option label="禁用" value="1" />
              </el-select>
            </el-form-item>

            <el-form-item label="创建时间">
              <el-date-picker
                class="!w-[240px]"
                v-model="dateTimeRange"
                type="daterange"
                range-separator="~"
                start-placeholder="开始时间"
                end-placeholder="截止时间"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleQuery">
                <i-ep-search />搜索
              </el-button>
              <el-button @click="resetQuery"> <i-ep-refresh />重置 </el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never" class="table-container">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button
                  v-hasPerm="['user@add']"
                  type="success"
                  @click="openDialog()"
                >
                  <i-ep-plus />新增
                </el-button>
                <el-button
                  v-hasPerm="['user@del']"
                  type="danger"
                  v-if="removeIds.length > 0"
                  @click="handleDelete()"
                >
                  <i-ep-delete />删除
                </el-button>
              </div>
              <div>
                <el-button
                  class="ml-3"
                  @click="handleSearchShowBtn"
                  icon="Search"
                  circle
                />
                <el-button
                  class="ml-3"
                  title="刷新"
                  @click="handleQuery"
                  icon="Refresh"
                  circle
                />
              </div>
            </div>
          </template>

          <el-table
            v-loading="loading"
            :data="pageData"
            @selection-change="handleSelectionChange"
            @sort-change="handleSortChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column
              key="id"
              label="ID"
              align="center"
              prop="id"
              width="100"
              sortable="custom"
            />
            <el-table-column label="头像" width="80px" align="center">
              <template #default="scope">
                <el-avatar :src="scope.row.avatar ?? avatar" />
              </template>
            </el-table-column>
            <el-table-column label="用户名" align="center" prop="username" />
            <el-table-column
              label="昵称"
              align="center"
              prop="nickname"
              width="135"
            />
            <el-table-column
              label="手机号码"
              align="center"
              prop="mobile"
              width="135"
            />
            <el-table-column
              label="邮箱"
              align="center"
              prop="email"
              width="165"
            />
            <el-table-column label="状态" align="center" prop="is_hid">
              <template #default="scope">
                <el-tag
                  effect="dark"
                  :type="scope.row.is_hid == 0 ? 'success' : 'danger'"
                >
                  {{ scope.row.is_hid == 0 ? "启用" : "禁用" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="创建时间"
              align="center"
              prop="created_at"
              width="160"
            />
            <el-table-column label="操作" fixed="right" width="145">
              <template #default="scope">
                <el-button
                  v-hasPerm="['user@resetpassword']"
                  type="primary"
                  circle
                  title="重置密码"
                  @click="resetPassword(scope.row)"
                >
                  <i-ep-refresh-left />
                </el-button>
                <el-button
                  v-hasPerm="['user@edit']"
                  type="success"
                  circle
                  title="编辑"
                  @click="openDialog(scope.row.id)"
                >
                  <i-ep-edit />
                </el-button>
                <el-button
                  v-hasPerm="['user@del']"
                  circle
                  type="danger"
                  title="删除"
                  @click="handleDelete(scope.row.id)"
                >
                  <i-ep-delete />
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.p"
            v-model:limit="queryParams.limit"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <!-- 用户新增/编辑表单 -->
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="formData.nickname" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="所属角色" prop="role_id">
          <el-cascader
            v-model="formData.role_id"
            :options="roleOptions"
            :props="cascaderProps"
            :show-all-levels="false"
            clearable
          />
        </el-form-item>
        <el-form-item label="所属组织" prop="org_id">
          <el-cascader
            v-model="formData.org_id"
            :options="orgTreeLst"
            :props="cascaderPropsTree"
            :show-all-levels="false"
            clearable
          />
        </el-form-item>
        <el-form-item label="所属岗位" prop="position_id">
          <el-select
            v-model="formData.position_id"
            placeholder="请选手所属岗位"
            clearable
          >
            <el-option
              v-for="item in positionLst"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input
            v-model="formData.mobile"
            placeholder="请输入手机号码"
            maxlength="11"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="formData.email"
            placeholder="请输入邮箱"
            maxlength="50"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="formData.password"
            placeholder="请输入账号密码"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="状态" prop="is_hid">
          <el-radio-group v-model="formData.is_hid">
            <el-radio :value="0">正常</el-radio>
            <el-radio :value="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "User",
  inheritAttrs: false,
});
import {
  getUserPage,
  getUserForm,
  deleteUsers,
  addUser,
  updateUser,
  updateUserPassword,
} from "@/api/user";
import { getRoleOptions } from "@/api/role";
import { orgTree } from "@/api/organization";
import { getPositionAll } from "@/api/position";
import { UserForm, UserQuery, UserPageVO } from "@/api/user/types";
const queryFormRef = ref(ElForm); // 查询表单
const userFormRef = ref(ElForm); // 用户表单
const isShowSearchBtn = ref(false);
const loading = ref(false); //  加载状态
const removeIds = ref([]); // 删除用户ID集合 用于批量删除
const queryParams = reactive<UserQuery>({
  p: 1,
  limit: 10,
  time: [] as any,
});
const dateTimeRange = ref([]);
const orgTreeLst = ref<OptionType[]>();
const positionLst = ref<OptionType[]>();
const total = ref(0); // 数据总数
const pageData = ref<UserPageVO[]>(); // 用户分页数据
const cascaderProps = ref({
  multiple: true,
  checkStrictly: true,
  emitPath: false,
});
const cascaderPropsTree = ref({
  multiple: true,
  checkStrictly: true,
  emitPath: false,
  children: "children",
  label: "title",
});
const defaultProps = ref({
  children: "children",
  label: "title",
});
const avatar = ref(
  new URL(`../../assets/images/avatar.png`, import.meta.url).href
);
const roleOptions = ref<OptionType[]>(); // 角色下拉数据源
// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: 800,
  title: "",
});
// 用户表单数据
const formData = reactive<UserForm>({
  is_hid: 0,
  password: "admin@admin",
});
// 校验规则
const rules = reactive({
  username: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
  nickname: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
  role_id: [{ required: true, message: "用户角色不能为空", trigger: "blur" }],
  email: [
    {
      required: true,
      pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
  mobile: [
    {
      required: true,
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});

watch(dateTimeRange, (newVal) => {
  Object.assign(queryParams, { time: newVal });
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getUserPage(queryParams)
    .then(({ data }) => {
      pageData.value = data.items;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleOrgQuery(data: any) {
  queryParams.org_id = data.id;
  handleQuery();
}

async function getOrgTree() {
  orgTree()
    .then(({ data }) => {
      orgTreeLst.value = data;
    })
    .finally(() => {});
}
async function positionAll() {
  getPositionAll().then((response) => {
    positionLst.value = response.data;
  });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  dateTimeRange.value = [];
  queryParams.p = 1;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 重置密码 */
function resetPassword(row: { [key: string]: any }) {
  ElMessageBox.prompt(
    "请输入用户「" + row.username + "」的新密码",
    "重置密码",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
    }
  ).then(({ value }) => {
    if (!value) {
      ElMessage.warning("请输入新密码");
      return false;
    }
    updateUserPassword(row.id, value).then(() => {
      ElMessage.success("密码重置成功，新密码是：" + value);
    });
  });
}

/** 加载角色下拉数据源 */
async function loadRoleOptions() {
  getRoleOptions().then((response) => {
    roleOptions.value = response.data;
  });
}

/**
 * 打开弹窗
 *
 * @param id 用户ID
 */
async function openDialog(id?: number) {
  dialog.visible = true;
  // 用户表单弹窗
  await loadRoleOptions();
  await positionAll();
  if (id) {
    dialog.title = "修改用户";
    getUserForm(id).then(({ data }) => {
      Object.assign(formData, { ...data });
      formData.password = "";
    });
  } else {
    dialog.title = "新增用户";
  }
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
  formData.id = undefined;
  formData.role_id = undefined;
  formData.is_hid = 0;
  handleQuery();
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  userFormRef.value.validate((valid: any) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      if (userId) {
        updateUser(formData)
          .then(() => {
            ElMessage.success("修改用户成功");
            closeDialog();
          })
          .finally(() => (loading.value = false));
      } else {
        addUser(formData)
          .then(() => {
            ElMessage.success("新增用户成功");
            closeDialog();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 3000);

/** 删除用户 */
function handleDelete(id?: number) {
  const userIds = id || removeIds.value;
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteUsers({ ids: userIds }).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

//收起展开搜索按钮
function handleSearchShowBtn() {
  isShowSearchBtn.value = isShowSearchBtn.value === false;
}

/** 排序 */
function handleSortChange(data: any) {
  const { prop, order } = data;
  if (prop === "id") {
    if (order === "ascending") {
      queryParams.sort = "+id";
    } else {
      queryParams.sort = "-id";
    }
    handleQuery();
  }
}

onMounted(() => {
  getOrgTree();
  handleQuery();
});
</script>
